/**  
 * @Project: Dawn
 * @Title: XmlParser.java
 * @Package util
 * @Description: XmlParser
 * @author yanglei yanglei1@funshion.com
 * @date 2014年12月2日 下午5:01:45
 * @Copyright: 2014 funshion.com. All rights reserved.
 * @version V1.0  
*/
package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @ClassName XmlParser
 * @Description Xml Parser
 * @author yanglei1 yanglei1@funshion.com
 * @date 2014年12月2日
 */
public class XmlParser {
	
	private String fileName;
	private Document document;
	private Element element;
	
	/**
	 * Constructor
	 * @param name
	 */
	public XmlParser(String name) {
		fileName = name;
		try {
			SAXReader reader = new SAXReader();
			InputStream in = new FileInputStream(new File(fileName));
			document = reader.read(in);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	/**
	 * get element by xpath and element attribute of ID
	 * @param xPath
	 * @param ID
	 * @return
	 */
	public Element getElementByID(String xPath, String ID) {
		@SuppressWarnings("unchecked")
		ArrayList<Element> eleList = (ArrayList<Element>) document.selectNodes(xPath);
		for (Element ele : eleList) {
			Attribute attribute = ele.attribute(0);
			if (attribute.getValue().equals(ID)) {
				element = ele;
			} 
		}
		return element;
	}
	
	@SuppressWarnings("unchecked")
	public List<Element> getElementByName(String name) {
		List<Element> elements = document.getRootElement().elements(name);
		for (Element ele : elements) {
			System.out.println(ele.asXML());
		}
		return elements;
	}
}
